package cn.huiyunche.driver.schedule;

import cn.huiyunche.base.service.constant.TmsUrlConstant;
import cn.huiyunche.base.service.enums.DWaybillStatusEnum;
import cn.huiyunche.base.service.enums.TmsUrlTypeEnum;
import cn.huiyunche.base.service.interfaces.TmsOrderCallHistoryService;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.OrderDepartureVo;
import cn.huiyunche.driver.service.OrderService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 确认发车定时任务
 *
 * @author hdy
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class DepartureOrdersQuartzCluster implements Job, Serializable {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger(DepartureOrdersQuartzCluster.class);

	/*@Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
		logger.info("jbo start: departure orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
		final String url = TmsUrlConstant.PULL_ORDER_DEPARTURE;
		TmsOrderCallHistoryService tmsOrderCallHistoryService = QuartzClusterFactory.getTmsOrderCallHistoryService();
		// 查询上一次成功url调用成功的记录
		Date lastTime = tmsOrderCallHistoryService.getLastTimeSuccess(TmsUrlTypeEnum.PULL_ORDER_DEPARTURE.getValue(), true);
		Map paramsMap = new HashedMap();
		paramsMap.put("lastTime", new DateTime(lastTime).toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
		String result = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_ORDER_DEPARTURE.getValue(),
				paramsMap);
		logger.info("zl departure order finish job result : {}.", result);
		if (StringUtils.isNotBlank(result)) {
			JSONObject jsonObject = JSONObject.parseObject(result);
			String data = jsonObject.getString("data");
			if (StringUtils.isNotBlank(data)) {
				List<OrderDepartureVo> departureResults = JSONArray.parseArray(data, OrderDepartureVo.class);
				if (CollectionUtils.isNotEmpty(departureResults)) {
					OrderService orderService = QuartzClusterFactory.getOrderService();
					orderService.orderDeparture(departureResults);
				}
			}
		}
		logger.info("jbo end: departure orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));

	}*/

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("jbo start: departure orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
        OrderService orderService = QuartzClusterFactory.getOrderService();
        String iorderids = orderService.getListByStatus(Arrays.asList(DWaybillStatusEnum.DEPARTURE.getValue()));
        if (StringUtils.isBlank(iorderids)) {
            logger.info("获取数据库中待发车数据【iorderids】为空 : {}，直接结束任务", iorderids);
            return;
        }
        Map<String, Object> paramsMap = new HashedMap<>();
        paramsMap.put("iorderids", iorderids);
        final String url = TmsUrlConstant.PULL_ORDER_DEPARTURE3;
        TmsOrderCallHistoryService tmsOrderCallHistoryService = QuartzClusterFactory.getTmsOrderCallHistoryService();
        String result = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_ORDER_DEPARTURE.getValue(),
                paramsMap, 30000);
        logger.info("zl departure order finish job result : {}.", result);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                List<OrderDepartureVo> departureResults = JSONArray.parseArray(data, OrderDepartureVo.class);
                if (CollectionUtils.isNotEmpty(departureResults)) {
                    try {
                        orderService.orderDeparture(departureResults);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        logger.info("jbo end: departure orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));

    }

}
